// cmd/plugins/asset-service/main.go
package main

import (
	"context"
	"encoding/json"
	goPlugin "github.com/hashicorp/go-plugin" // 使用别名
	"google.golang.org/grpc"
	"log"
	"platform/proto/plugin"
)

// AssetService 实现插件服务
type AssetService struct {
	plugin.UnimplementedPluginServer
}

func (s *AssetService) GetInfo(ctx context.Context, empty *plugin.Empty) (*plugin.PluginInfo, error) {
	return &plugin.PluginInfo{
		Name:        "asset-service",
		Version:     "1.0.0",
		Methods:     []string{"GET", "POST", "PUT", "DELETE"},
		Description: "数字资产服务插件",
	}, nil
}

func (s *AssetService) Handle(ctx context.Context, req *plugin.Request) (*plugin.Response, error) {
	log.Printf("AssetService 收到请求: %s %s, 用户: %s", req.Method, req.Path, req.UserId)

	// 模拟处理不同的请求
	var responseBody []byte
	var statusCode int32

	switch req.Method {
	case "GET":
		if req.Path == "/assets" {
			// 返回资产列表
			assets := map[string]interface{}{
				"assets": []map[string]interface{}{
					{"id": "1", "name": "资产1", "type": "image"},
					{"id": "2", "name": "资产2", "type": "document"},
				},
				"count": 2,
			}
			responseBody, _ = json.Marshal(assets)
			statusCode = 200
		} else {
			responseBody, _ = json.Marshal(map[string]string{"error": "未找到资源"})
			statusCode = 404
		}
	case "POST":
		responseBody, _ = json.Marshal(map[string]string{"message": "资产创建成功"})
		statusCode = 201
	default:
		responseBody, _ = json.Marshal(map[string]string{"error": "不支持的请求方法"})
		statusCode = 405
	}

	return &plugin.Response{
		StatusCode: statusCode,
		Headers:    map[string]string{"Content-Type": "application/json"},
		Body:       responseBody,
	}, nil
}

func (s *AssetService) HealthCheck(ctx context.Context, empty *plugin.Empty) (*plugin.HealthStatus, error) {
	return &plugin.HealthStatus{
		Healthy: true,
		Message: "资产服务运行正常",
	}, nil
}

// AssetPlugin 实现 hashicorp/go-plugin 的 Plugin 接口
type AssetPlugin struct {
	goPlugin.Plugin // 使用别名
}

func (p *AssetPlugin) GRPCServer(broker *goPlugin.GRPCBroker, s *grpc.Server) error {
	plugin.RegisterPluginServer(s, &AssetService{})
	return nil
}

func (p *AssetPlugin) GRPCClient(ctx context.Context, broker *goPlugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) {
	return plugin.NewPluginClient(c), nil
}

func main() {
	goPlugin.Serve(&goPlugin.ServeConfig{ // 使用别名
		HandshakeConfig: goPlugin.HandshakeConfig{
			ProtocolVersion:  1,
			MagicCookieKey:   "PLATFORM_PLUGIN",
			MagicCookieValue: "zhitu-platform",
		},
		Plugins: map[string]goPlugin.Plugin{
			"plugin": &AssetPlugin{},
		},
		GRPCServer: goPlugin.DefaultGRPCServer,
	})
}
